package com.morningstar.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.morningstar.system.dao.entity.SysUser;
import com.morningstar.system.dao.entity.SysUserRole;
import com.morningstar.system.dao.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 *
 * @author yanglianshan
 * @since 2023-06-28
 */
@Slf4j
@Service
public class SysUserRoleService extends ServiceImpl<SysUserRoleMapper, SysUserRole> {


    @Transactional(rollbackFor = Exception.class)
    public void addUserRole(SysUser sysUser) {
        this.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, sysUser.getUserId()));
        List<SysUserRole> userRoleList = new ArrayList<>();
        SysUserRole userRole;
        for (Long roleId : sysUser.getRoleIds()) {
            userRole = new SysUserRole();
            userRole.setUserId(sysUser.getUserId());
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }
        this.saveBatch(userRoleList);
    }

}
